use std::sync::{
    atomic::{AtomicBool, Ordering},
    Arc,
};

use anyhow::Result;
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};

#[tokio::main]
async fn main() -> Result<()> {
    let running = Arc::new(AtomicBool::new(true));
    let r = running.clone();

    ctrlc::set_handler(move || {
        r.store(false, Ordering::SeqCst);
    })
    .expect("Error setting Ctrl-C handler");

    let host = cpal::default_host();
    let device = host
        .default_input_device()
        .expect("failed to find input device.");

    let config = device
        .default_input_config()
        .expect("failed to get default input config.");

    let stream = device.build_input_stream(
        &config.into(),
        |data: &[f32], _| {
            println!("data: {}", data.len());
        },
        move |err| {},
        None,
    )?;

    stream.play()?;

    while running.load(Ordering::SeqCst) {}

    Ok(())
}
